<template>
  <Dialog v-model="dialogVisible" :title="formType === 'create' ? '评分录入' : '评分修改'" width="900px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价计划" prop="planId">
            <el-select
              v-model="formData.planId"
              placeholder="请选择评价计划"
              clearable
              filterable
              style="width: 100%"
              @change="handlePlanChange"
              :disabled="formType === 'update'"
            >
              <el-option
                v-for="plan in planList"
                :key="plan.id"
                :label="plan.planName"
                :value="plan.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评价科目" prop="subjectId">
            <el-select
              v-model="formData.subjectId"
              placeholder="请选择评价科目"
              clearable
              filterable
              style="width: 100%"
              :disabled="formType === 'update'"
              @change="handleSubjectChange"
            >
              <el-option
                v-for="subject in subjectList"
                :key="subject.id"
                :label="`${subject.subjectName} (${subject.subjectCode})`"
                :value="subject.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="科目代码">
            <el-input
              v-model="formData.subjectCode"
              placeholder="选择科目后自动填写"
              readonly
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参评人员" prop="candidateId">
            <el-select
              v-model="formData.candidateId"
              placeholder="请选择参评人员"
              clearable
              filterable
              style="width: 100%"
              :disabled="formType === 'update'"
            >
              <el-option
                v-for="candidate in candidateList"
                :key="candidate.id"
                :label="candidate.name"
                :value="candidate.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考评员" prop="evaluatorId">
            <el-select
              v-model="formData.evaluatorId"
              placeholder="请选择考评员"
              clearable
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="evaluator in evaluatorList"
                :key="evaluator.id"
                :label="evaluator.nickname"
                :value="evaluator.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 评分信息 -->
      <el-divider content-position="left">评分信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="理论成绩" prop="theoryScore">
            <el-input-number
              v-model="formData.theoryScore"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="请输入理论成绩"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实操成绩" prop="practiceScore">
            <el-input-number
              v-model="formData.practiceScore"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="请输入实操成绩"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="综合成绩">
            <el-input-number
              v-model="formData.totalScore"
              :min="0"
              :max="100"
              :precision="1"
              placeholder="自动计算"
              readonly
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="满分">
            <el-input-number
              v-model="formData.maxScore"
              :min="1"
              :max="200"
              :precision="0"
              placeholder="满分"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否通过">
            <el-tag :type="formData.isPassed ? 'success' : 'danger'">
              {{ formData.isPassed ? '通过' : '不通过' }}
            </el-tag>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="评分状态" prop="scoreStatus">
            <el-select
              v-model="formData.scoreStatus"
              placeholder="请选择评分状态"
              style="width: 100%"
            >
              <el-option label="草稿" :value="0" />
              <el-option label="已提交" :value="1" />
              <el-option label="已确认" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="评价意见">
        <el-input
          v-model="formData.evaluatorComments"
          type="textarea"
          :rows="3"
          placeholder="请输入评价意见（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="评分备注">
        <el-input
          v-model="formData.scoreComments"
          type="textarea"
          :rows="2"
          placeholder="请输入评分备注（可选）"
          maxlength="300"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false" :disabled="formLoading">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">
        {{ formLoading ? '提交中...' : '确 定' }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createScoreRecord, updateScoreRecord } from '@/api/eval/score'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import { EvalSubjectVO, getSubjectListByPlanId } from '@/api/eval/subject'
import { EvalCandidateInfoVO, getCandidateInfoListByPlanId } from '@/api/eval/candidate/index'
import { UserVO, getSimpleUserList } from '@/api/system/user'

defineOptions({ name: 'ScoreForm' })

const emit = defineEmits(['success'])

const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formType = ref<'create' | 'update'>('create')

// 下拉选项数据
const planList = ref<EvalPlanVO[]>([])
const subjectList = ref<EvalSubjectVO[]>([])
const candidateList = ref<EvalCandidateInfoVO[]>([])
const evaluatorList = ref<UserVO[]>([])

const formData = ref({
  id: undefined,
  planId: undefined,
  candidateId: undefined,
  subjectId: undefined,
  subjectCode: '', // 科目代码
  evaluatorId: undefined,
  theoryScore: 0,
  practiceScore: 0,
  totalScore: 0,
  maxScore: 100,
  scoreDetails: '',
  sectionScores: '',
  scoreComments: '',
  evaluatorComments: '',
  isPassed: false,
  scoreStatus: 0, // 0-草稿 1-已提交 2-已确认
  isReviewed: false,
  reviewerId: undefined,
  reviewTime: undefined,
  reviewComments: '',
  submitTime: undefined,
  confirmTime: undefined
})

// 表单验证规则
const formRules = {
  planId: [
    { required: true, message: '请选择评价计划', trigger: 'change' }
  ],
  subjectId: [
    { required: true, message: '请选择评价科目', trigger: 'change' }
  ],
  candidateId: [
    { required: true, message: '请选择参评人员', trigger: 'change' }
  ],
  evaluatorId: [
    { required: true, message: '请选择考评员', trigger: 'change' }
  ],
  theoryScore: [
    { required: true, message: '请输入理论成绩', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '成绩范围为0-100', trigger: 'blur' }
  ],
  practiceScore: [
    { required: true, message: '请输入实操成绩', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '成绩范围为0-100', trigger: 'blur' }
  ],
  scoreStatus: [
    { required: true, message: '请选择评分状态', trigger: 'change' }
  ]
}

// 计算综合成绩
watch([() => formData.value.theoryScore, () => formData.value.practiceScore], () => {
  const theory = formData.value.theoryScore || 0
  const practice = formData.value.practiceScore || 0
  formData.value.totalScore = Math.round((theory + practice) / 2 * 10) / 10 // 保留一位小数

  // 计算是否通过（假设60分及格）
  formData.value.isPassed = formData.value.totalScore >= 60
})

// 计划变更处理
const handlePlanChange = async (planId: number) => {
  if (planId) {
    try {
      // 加载科目列表
      subjectList.value = await getSubjectListByPlanId(planId)
      // 加载参评人员列表
      candidateList.value = await getCandidateInfoListByPlanId(planId)
    } catch (error) {
      console.error('加载计划相关数据失败:', error)
      ElMessage.error('加载计划相关数据失败')
    }
  } else {
    subjectList.value = []
    candidateList.value = []
  }
  // 清空相关字段
  formData.value.subjectId = undefined
  formData.value.subjectCode = ''
  formData.value.candidateId = undefined
}

// 科目变更处理
const handleSubjectChange = (subjectId: number) => {
  if (subjectId) {
    const subject = subjectList.value.find(s => s.id === subjectId)
    if (subject) {
      formData.value.subjectCode = subject.subjectCode || ''
      // 设置科目的满分
      formData.value.maxScore = subject.maxScore || 100
    }
  } else {
    formData.value.subjectCode = ''
    formData.value.maxScore = 100
  }
}

/** 打开弹窗 */
const open = async (type: 'create' | 'update', data?: any) => {
  dialogVisible.value = true
  formType.value = type
  resetForm()

  // 加载基础数据
  await loadBasicData()

  if (data) {
    Object.assign(formData.value, data)

    // 如果是编辑模式且有计划ID，加载相关数据
    if (type === 'update' && data.planId) {
      await handlePlanChange(data.planId)
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    candidateId: undefined,
    subjectId: undefined,
    subjectCode: '',
    evaluatorId: undefined,
    theoryScore: 0,
    practiceScore: 0,
    totalScore: 0,
    maxScore: 100,
    scoreDetails: '',
    sectionScores: '',
    scoreComments: '',
    evaluatorComments: '',
    isPassed: false,
    scoreStatus: 0,
    isReviewed: false,
    reviewerId: undefined,
    reviewTime: undefined,
    reviewComments: '',
    submitTime: undefined,
    confirmTime: undefined
  }

  // 清空下拉选项
  subjectList.value = []
  candidateList.value = []

  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    formLoading.value = true

    // 构建评分详情JSON
    const scoreDetails = {
      theoryScore: Number(formData.value.theoryScore),
      practiceScore: Number(formData.value.practiceScore),
      breakdown: {
        theory: {
          score: Number(formData.value.theoryScore),
          maxScore: 100,
          percentage: Number(formData.value.theoryScore)
        },
        practice: {
          score: Number(formData.value.practiceScore),
          maxScore: 100,
          percentage: Number(formData.value.practiceScore)
        }
      }
    }

    // 构建分项得分JSON
    const sectionScores = {
      theory: Number(formData.value.theoryScore),
      practice: Number(formData.value.practiceScore)
    }

    const data = {
      ...formData.value,
      // 确保数值类型正确
      totalScore: Number(formData.value.totalScore),
      maxScore: Number(formData.value.maxScore),
      scoreDetails: JSON.stringify(scoreDetails),
      sectionScores: JSON.stringify(sectionScores)
    }

    if (formType.value === 'create') {
      await createScoreRecord(data)
      ElMessage.success('评分录入成功')
    } else {
      await updateScoreRecord(data)
      ElMessage.success('评分更新成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交评分失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    formLoading.value = false
  }
}

/** 加载基础数据 */
const loadBasicData = async () => {
  try {
    // 加载计划列表（审核通过的计划：已审批、已发布、进行中）
    const approvedPlans = await getPlanListByStatus(2) // 已审批
    const publishedPlans = await getPlanListByStatus(3) // 已发布
    const inProgressPlans = await getPlanListByStatus(4) // 进行中
    planList.value = [...approvedPlans, ...publishedPlans, ...inProgressPlans]

    // 加载考评员列表（系统用户）
    const userList = await getSimpleUserList()
    evaluatorList.value = userList || []
  } catch (error) {
    console.error('加载基础数据失败:', error)
    ElMessage.error('加载基础数据失败')
  }
}

/** 初始化 */
onMounted(() => {
  loadBasicData()
})

defineExpose({ open })
</script>